

//
//  RadarViewController.m
//  广告页
//
//  Created by YYY on 2017/2/21.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

#import "RadarViewController.h"

#import "NewViewController.h"

//图片缓存
#import "UIImageView+WebCache.h"

//地图定位
#import <CoreLocation/CoreLocation.h>

#import "HYBaseHttpTools.h"

#define kDeviceWidth [UIScreen mainScreen].bounds.size.width


@interface RadarViewController () <CLLocationManagerDelegate>
{
    //纬度
    NSString *latitude;
    //经度
    NSString *longitude;
    
    UIImageView *avatarView;
    
    NSInteger locationFlag;
}
@property (nonatomic, strong) NSArray *pointsArray;
@property (nonatomic, strong) NSArray *imagesArray;

//定位
@property(nonatomic,strong)UIButton *locationCity;
//定位管理器
@property(nonatomic,strong)CLLocationManager *locationManager;

@end

@implementation RadarViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    locationFlag = 0;
    self.title = @"雷达";
    //定位方法
    [self locationManagerMethod];
    //初始化雷达视图
    [self initRadarView];
    
    //加载网络数据
    [self loadNetworkData];
   
    // Do any additional setup after loading the view.
}

-(CLLocationManager *)locationManager
{
    if (!_locationManager)
    {
        _locationManager = [[CLLocationManager alloc]init];
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        //设置移动多少距离后更新位置
        self.locationManager.distanceFilter = 1000;
    }
    return _locationManager;
}

-(UIButton *)locationCity
{
    if (!_locationCity)
    {
        _locationCity = [UIButton buttonWithType:UIButtonTypeCustom];
        _locationCity.frame = CGRectMake(0, 0, 50, 30);
        [_locationCity setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        _locationCity.titleLabel.font = [UIFont systemFontOfSize:14];
        [_locationCity setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
        [_locationCity addTarget:self action:@selector(_locationCityAction:) forControlEvents:UIControlEventTouchUpInside];
        
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:_locationCity];
    }
    return _locationCity;
}

-(void)_locationCityAction:(UIButton *)locationBtn
{
    NewViewController *newVC = [[NewViewController alloc]init];
    NSLog(@"didSelectItemAtIndex:%lu", (unsigned long)index);
    [self.navigationController pushViewController:newVC animated:YES];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (locationFlag!=0)
    {
        [self.locationManager startUpdatingLocation];
    }
    locationFlag++;
}
//定位方法
-(void)locationManagerMethod
{
    if(!CLLocationManager.locationServicesEnabled)
    {
        //不允许定位选择项
        [self unableLocation];
        //NSLog(@"无法定位，因为您的设备没有启用定位服务，请到设置中启用");
        //[UILabel showErrorProgressLabelWithString:@"无法定位，因为您的设备没有启用定位服务，请到设置中启用"];
        return;
    }
    
    if (CLLocationManager.authorizationStatus == kCLAuthorizationStatusNotDetermined)
    {
        [self.locationManager requestWhenInUseAuthorization];
    }
    //状态为，用户在设置-定位中选择了【永不】，就是不允许App使用定位服务
    else if(CLLocationManager.authorizationStatus == kCLAuthorizationStatusDenied)
    {
        //不允许定位选择项
        [self unableLocation];
    }
    self.locationManager.delegate = self;
    [self.locationManager startUpdatingLocation];
}

//不允许定位选择项
-(void)unableLocation
{
    NSString *titleStr = @"无法定位，因为您没有授权本应用程序使用定位，请至设置中开启！";
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:titleStr preferredStyle:(UIAlertControllerStyleAlert)];
    [self presentViewController:alertController animated:YES completion:^{
        
    }];
    //确定
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action)
                                 {
                                     //跳转设置界面
                                     [self goToSettingPage];
                                 }];
    [alertController addAction:sureAction];
    
    //取消
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action)
                                   {
                                   }];
    [alertController addAction:cancelAction];
}

//跳转设置界面
-(void)goToSettingPage
{
    //需要把弹窗放在主线程才能强制显示
    dispatch_async(dispatch_get_main_queue(), ^{
        UIKIT_EXTERN NSString *const UIApplicationOpenSettingsURLString NS_AVAILABLE_IOS(8_0);
        
        //去设置
        NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if([[UIApplication sharedApplication] canOpenURL:settingURL])
        {
            [[UIApplication sharedApplication] openURL:settingURL];
        }
        return;
    });
}
#pragma mark CLLocationManager delegate
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    //定位管理器 停止定位
    [manager stopUpdatingLocation];
    
    CLLocation *location = locations[0];
    //纬度
    latitude = [NSString stringWithFormat:@"%f",location.coordinate.latitude];
    //经度
    longitude = [NSString stringWithFormat:@"%f",location.coordinate.longitude];
    
    CLGeocoder* geocoder=[[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:location
                   completionHandler:^(NSArray *placemarks, NSError *error)
     {
         if (placemarks.count>0)
         {
             CLPlacemark *placemark=(CLPlacemark*)[placemarks lastObject];
             //具体地址
             NSString *name = placemark.name;
             //当前城市
             NSString *city = placemark.locality;
             //当前国家
             NSString *country = placemark.country;
             //当前位置
             NSString *subLocality = placemark.subLocality;
             //当前街道
             NSString *thoroughfare = placemark.thoroughfare;
             [self.locationCity setTitle:thoroughfare forState:UIControlStateNormal];
             CGFloat width = [self.locationCity.currentTitle boundingRectWithSize:CGSizeMake(MAXFLOAT, 30) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : _locationCity.titleLabel.font} context:nil].size.width;
             self.locationCity.frame = CGRectMake(0, 0, width, 30);
             if (!city)
             {
                 //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                 city = placemark.administrativeArea;
             }
         }
     }];
}

//权限验证
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status)
    {
        case kCLAuthorizationStatusNotDetermined:
            if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
            {
                [self.locationManager requestWhenInUseAuthorization];
            }
            break;
        default:
            break;
    }
}


//初始化雷达视图
-(void)initRadarView
{
    XHRadarView *radarView = [[XHRadarView alloc] initWithFrame:self.view.bounds];
    radarView.dataSource = self;
    radarView.delegate = self;
    radarView.radius = (kDeviceWidth-40)/2.0;
    //radarView.backgroundColor = [UIColor colorWithRed:0.251 green:0.329 blue:0.490 alpha:1];
    radarView.backgroundImage = [UIImage imageNamed:@"radar_background"];
    radarView.labelText = @"正在搜索附近的目标";
    [self.view addSubview:radarView];
    _radarView = radarView;
    
    avatarView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.center.x-30, self.view.center.y-30, 60, 60)];
    avatarView.layer.cornerRadius = 30;
    avatarView.layer.masksToBounds = YES;
    [_radarView addSubview:avatarView];
    [_radarView bringSubviewToFront:avatarView];
    
    [self.radarView scan];
    [self startUpdatingRadar];
}

#pragma mark - Custom Methods
- (void)startUpdatingRadar
{
    typeof(self) __weak weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        weakSelf.radarView.labelText = [NSString stringWithFormat:@"搜索已完成，共找到%lu个目标", (unsigned long)weakSelf.pointsArray.count];
        [weakSelf.radarView show];
    });
}

//加载网络数据
-(void)loadNetworkData
{
    [[HYBaseHttpTools shareHYBaseHttpTools] commonInterfaceRequestHttpToolPostConvertList:nil urlString:@"http://172.168.1.40:8185/custom/games/getAllActivityTitleAndTime.json" success:^(NSDictionary *responseObject)
     {
         [avatarView sd_setImageWithURL:[NSURL URLWithString:@"https://imgsa.baidu.com/baike/c0%3Dbaike80%2C5%2C5%2C80%2C26/sign=a7acbd53f41f4134f43a0d2c4476feaf/b999a9014c086e061c271ffb0b087bf40bd1cbf6.jpg"] placeholderImage:[UIImage imageNamed:@"image1.jpg"]];
         
         //目标点位置
         _pointsArray = @[
                          @[@6, @90],
                          @[@-140, @108],
                          @[@-83, @98],
                          @[@-25, @142],
                          @[@60, @111],
                          @[@-111, @96],
                          @[@150, @145],
                          @[@25, @144],
                          @[@-55, @110],
                          @[@95, @109],
                          @[@170, @165],
                          @[@125, @112],
                          @[@-150, @145],
                          @[@-7, @160],
                          ];
         
         _imagesArray = @[@"http://up.qqjia.com/z/03/tu4523_4.jpg",@"http://up.qqya.com/allimg/201710-t/17-101803_106599.jpg",@"http://up.qqya.com/allimg/201710-t/17-101803_106598.jpg",@"http://up.qqya.com/allimg/201710-t/17-101803_106611.jpg",@"http://up.qqya.com/allimg/201710-t/17-101803_106606.jpg",@"http://up.qqya.com/allimg/201710-t/17-101803_106610.jpg",@"http://img.zcool.cn/community/01392d578c4cb60000018c1ba15f76.JPG",@"http://hellorfimg.zcool.cn/preview/245987983.jpg",@"http://img05.tooopen.com/images/20141217/sy_77493739982.jpg",@"http://img3.redocn.com/20131012/Redocn_2013101208320171.jpg",@"https://ss0.baidu.com/6ONWsjip0QIZ8tyhnq/it/u=1598552568,4236159349&fm=58",@"http://tupian.enterdesk.com/2013/mxy/10/12/1/16.jpg",@"http://pic31.photophoto.cn/20140602/0034034486544673_b.jpg",@"https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2288007548,1430516479&fm=111&gp=0.jpg"];
     } fail:^(NSError *error)
     {
         
     }];
}
#pragma mark - XHRadarViewDataSource
- (NSInteger)numberOfSectionsInRadarView:(XHRadarView *)radarView
{
    return 5;
}
- (NSInteger)numberOfPointsInRadarView:(XHRadarView *)radarView {
    return [self.pointsArray count];
}
- (UIView *)radarView:(XHRadarView *)radarView viewForIndex:(NSUInteger)index
{
    UIView *pointView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 35, 35)];
    //pointView.backgroundColor = [UIColor redColor];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 35, 35)];
    imageView.layer.masksToBounds = YES;
    imageView.layer.cornerRadius = 35/2.0;
    [imageView sd_setImageWithURL:[NSURL URLWithString:_imagesArray[index]] placeholderImage:[UIImage imageNamed:@"image1.jpg"]];
    [pointView addSubview:imageView];
    
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 5;
    //animation.cumulative = YES;
    animation.repeatCount = INT_MAX;
    animation.removedOnCompletion = NO;
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.8, 0.8, 1.0)]];
     [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1, 1.1, 1.0)]];
     [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.8, 0.8, 1.0)]];
    animation.values = values;
    [imageView.layer addAnimation:animation forKey:nil];
      return pointView;
}
- (CGPoint)radarView:(XHRadarView *)radarView positionForIndex:(NSUInteger)index
{
    NSArray *point = [self.pointsArray objectAtIndex:index];
    return CGPointMake([point[0] floatValue], [point[1] floatValue]);
}

#pragma mark - XHRadarViewDelegate

- (void)radarView:(XHRadarView *)radarView didSelectItemAtIndex:(NSUInteger)index
{
    NewViewController *newVC = [[NewViewController alloc]init];
    NSLog(@"didSelectItemAtIndex:%lu", (unsigned long)index);
    [self.navigationController pushViewController:newVC animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
